package cn.xxstudy.blog.config

import org.slf4j.LoggerFactory
import org.springframework.beans.FatalBeanException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.servlet.ModelAndView
import java.lang.reflect.InvocationTargetException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 作者：wuxinxi on 2020/11/24
 * 包名：cn.xxstudy.blog.config
 * TODO:全局异常处理
 */
@ControllerAdvice
class GlobalControllerException {
    private val logger = LoggerFactory.getLogger(this::class.java)

    @ExceptionHandler(Exception::class)
    fun handleNotReadableException(request: HttpServletRequest, e: Exception): ModelAndView {
        logger.error("Request url:${request.requestURL}", e)
        val modelAndView = ModelAndView()
        modelAndView.addObject("url", request.requestURL)
        modelAndView.addObject("exception", e)
        modelAndView.viewName = "error/500"
        if (e is FatalBeanException) {
            modelAndView.viewName = "error/404"
        }
        return modelAndView
    }
}
 